package com.yang.core.service;

import com.yang.security.utils.UserUtils;
import com.yang.service.api.AddrService;
import com.yang.core.dao.AddressRepository;
import com.yang.core.model.Address;
import com.yang.service.model.dto.post.AddrPostDTO;
import com.yang.service.model.dto.put.AddrPutDTO;
import com.yang.service.model.vo.AddrVo;
import com.zhy.base.exception.model.ExceptionEnum;
import com.zhy.base.exception.utils.AssertHelper;
import com.zhy.base.tools.beans.BeanMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.web.bind.annotation.*;
import javax.transaction.Transactional;
import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.List;

/**
 * Created by xin7k
 * Date: 2019/12/2
 */
@Slf4j
@RestController
@RequestMapping("addr")
@Api(tags = "地址操作API", description = "Addr")
public class AddrServiceImpl implements AddrService {
    @Autowired
    private BeanMapper beanMapper;
    @Autowired
    private AddressRepository addressRepository;

    @ApiOperation("保存地址")
    @PostMapping
    @Transactional
    @Override
    public String save(@Valid AddrPostDTO dto,String id) {
        Address address = beanMapper.map(dto,Address.class);
        address.setUserId(id);
        address.setCreateTime(LocalDateTime.now());
        addressRepository.save(address);
        return "保存成功";
    }

    @ApiOperation("根据用户Id批量查询")
    @GetMapping("list")
    @Override
    public List<AddrVo> selectList(String userId) {

        Address address = new Address();
        address.setUserId(userId);
        Example<Address> example = Example.of(address);
        List<Address> all = addressRepository.findAll(example);
        List<AddrVo> list = beanMapper.mapList(all,AddrVo.class);
        return list;
    }

    @ApiOperation("根据地址Id更新")
    @PutMapping("{id}")
    @Override
    public boolean update(String id, @Valid AddrPutDTO dto) {
        Address map = beanMapper.map(dto, Address.class);
        map.setId(id);
        boolean update = addressRepository.update(map);
        log.info("save返回值为" + update);
        return true;
    }

    @ApiOperation("根据地址Id更新")
    @DeleteMapping("{id}")
    @Override
    public boolean deleteById(String id) {
        addressRepository.deleteById(id);
        return true;
    }

    @ApiOperation("根据批量删除")
    @DeleteMapping("batch")
    @Override
    public boolean deleteBatch(List<String> strings) {
        AssertHelper.isNullWithCollection(strings, ExceptionEnum.FEIGN_PARAMS_ERROR);
        addressRepository.logicDeleteBatch(strings);
        return false;
    }
}
